package com.my.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.my.file.service.FileStorageService;
import com.my.model.common.dtos.PageResponseResult;
import com.my.model.common.dtos.ResponseResult;
import com.my.model.common.enums.AppHttpCodeEnum;
import com.my.model.wemedia.dtos.WmMaterialDto;
import com.my.model.wemedia.pojos.WmMaterial;
import com.my.model.wemedia.pojos.WmNews;
import com.my.model.wemedia.pojos.WmUser;
import com.my.utils.thread.WmThreadLocalUtils;
import com.my.wemedia.mapper.WmMaterialMapper;
import com.my.wemedia.service.WmMaterialService;
import com.my.wemedia.service.WmNewsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.*;

@Slf4j
@Service
@Transactional
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {
    @Autowired
    private FileStorageService fileStorageService;

    /**
     * 获取素材列表
     * @param wmMaterialDto
     * @return
     */
    @Override
    public PageResponseResult findList(WmMaterialDto wmMaterialDto) {
        //检查参数
        wmMaterialDto.checkParam();

        //分页查询
        IPage<WmMaterial> page = new Page<>(wmMaterialDto.getPage(),wmMaterialDto.getSize());
        LambdaQueryWrapper<WmMaterial> lqw = new LambdaQueryWrapper<>();
        //查询是否收藏
        if(wmMaterialDto.getIsCollection() != null && wmMaterialDto.getIsCollection() == 1) {
            lqw.eq(WmMaterial::getIsCollection,wmMaterialDto.getIsCollection());
        }
        //根据用户id查询
        lqw.eq(WmThreadLocalUtils.getUser().getId() != null,WmMaterial::getUserId,WmThreadLocalUtils.getUser().getId());
        //按照时间倒序排序
        lqw.orderByDesc(WmMaterial::getCreatedTime);

        IPage<WmMaterial> iPage = page(page, lqw);

        //返回结果
        PageResponseResult pageResponseResult = new PageResponseResult(wmMaterialDto.getPage(), wmMaterialDto.getSize(), (int) iPage.getTotal());
        pageResponseResult.setData(iPage.getRecords());
        return pageResponseResult;
    }

    /**
     * 上传素材图片
     * @param multipartFile
     * @return
     */
    @Override
    public ResponseResult uploadPicture(MultipartFile multipartFile) {
        //1.检查参数
        if(multipartFile == null || multipartFile.getSize() == 0 ) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //2.上传图片到minio
        String fileName = UUID.randomUUID().toString().replace("-","");
        //获取图片后缀
        String originalFileName = multipartFile.getOriginalFilename();
        String postfix = originalFileName.substring(originalFileName.lastIndexOf("."));
        String fileId = null;

        try {
            fileId = fileStorageService.uploadImgFile("",fileName + postfix, multipartFile.getInputStream());
            log.info("上传图片至minio中，fileId:{}",fileId);
        } catch (IOException e) {
            log.error("WmMaterialService上传文件失败！");
            e.printStackTrace();
        }

        //3.保存数据到数据库
        WmMaterial wmMaterial = new WmMaterial();
        wmMaterial.setUserId(WmThreadLocalUtils.getUser().getId());
        wmMaterial.setUrl(fileId);
        wmMaterial.setCreatedTime(LocalDateTime.now());
        wmMaterial.setType((short) 0);   //存储类型 0表示图片 1表示视频
        wmMaterial.setIsCollection((short) 0);  //是否收藏
        this.save(wmMaterial);

        return ResponseResult.okResult(wmMaterial);
    }

    @Autowired
    private WmNewsService wmNewsService;
    /**
     * 删除素材
     * @param id
     * @return
     */
    @Override
    public ResponseResult deleteMaterial(Integer id) {
        //参数校验
        if(id == null) return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);

        log.info("请求删除素材...");
        //1.获取创作者id
        Integer userId = WmThreadLocalUtils.getUser().getId();
        //2.获取该作者所有作品
        LambdaQueryWrapper<WmNews> lqw = new LambdaQueryWrapper<>();
        lqw.eq(WmNews::getUserId,userId);
        List<WmNews> wmNewList = wmNewsService.list(lqw);

        //3.获取作品所有素材信息
        List<String> materialList = getNewsImage(wmNewList);

        //4.获取待删除素材地址
        LambdaQueryWrapper<WmMaterial> lqw1 = new LambdaQueryWrapper<>();
        lqw1.eq(WmMaterial::getId,id);
        WmMaterial material = this.getOne(lqw1);
        String url = material.getUrl();

        //5.文章中引用了该素材，不能删除
        if(materialList.contains(url)) {
            log.info("素材被其它文章引用，不能删除!");
            return ResponseResult.errorResult(AppHttpCodeEnum.MATERIAL_REFERENCED);
        }

        //6.图片素材未被引用，可以删除
        //6.1删除minio文件
        fileStorageService.delete(url);
        log.info("成功删除MinIO中素材信息");

        //6.2更新数据库
        this.removeById(id);
        log.info("删除数据库中素材信息");

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 获取文章中图片素材信息
     * @param wmNewList
     * @return
     */
    private List<String> getNewsImage(List<WmNews> wmNewList) {
        //存储图片链接
        List<String> imageUrlList = new ArrayList<>();

        for (WmNews wmNews : wmNewList) {
            //1.从文章内容中提取文本及图片
            if(StringUtils.isNotBlank(wmNews.getContent())) {
                List<Map> maps = JSON.parseArray(wmNews.getContent(),Map.class);
                for (Map map : maps) {
                    if(map.get("type").equals("image")) {
                        //图片
                        imageUrlList.add((String) map.get("value"));
                    }
                }
            }

            //2.从封面中提取图片
            if(StringUtils.isNotBlank(wmNews.getImages())) {
                Collections.addAll(imageUrlList, wmNews.getImages().split(","));
            }
        }
        //3.结果返回
        return imageUrlList;
    }
}
